package com.androiddatasender;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Receiver extends Thread implements Context {

	private Socket sck = null;
	private DataInputStream dis = null;
	private ReceiveCallback callback = null;
	private boolean running = true;
	private DataOutputStream dos = null;

	public Receiver(Socket sck, ReceiveCallback callback) {
		
		this.sck = sck;
		this.callback = callback;
		try {
			dos = new DataOutputStream(sck.getOutputStream());
			dis = new DataInputStream(sck.getInputStream());
		} catch (IOException e) {
		}
	}

	public void run() {
		byte[] buffer = new byte[65535*2];
		while (running) {
            boolean reconnectNeeded = false;
			try {
				int sz = dis.read(buffer, 0, buffer.length);
				if (sz <= 0) {
                    reconnectNeeded = true;
                }
			} catch (IOException ioe) {
                reconnectNeeded = true;
			}

            if (reconnectNeeded) {
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException ire)
                {}
                Net.getInstance().connect();
                break;
            }
		}
	}

	public void send(Msg msg) { // send 1 : 1 connection
		try {
            byte[] buffer = msg.packet.toByteArray();           
            dos.write(buffer, 0, buffer.length);
            dos.flush();
        } catch (IOException e) {
        }
	}
	
	public void shutdown() {
		this.running = false;
		try {
			sck.close();
		} catch (IOException ioe) {
		}
	}

}
